<?php
/**
 * Converts HTML entities to their boring XML-compatible versions.
 */
class Entities {
	 static $entity_map = null;
	 static $entity_regex = '';

	public static function revert_entities($html) {
		if (Entities::$entity_map == null) {
			Entities::load_entity_map();
		}
		$result = '';
		while (preg_match(Entities::$entity_regex, $html, $m, PREG_OFFSET_CAPTURE)) {
			$result .= substr($html, 0, $m[0][1]);
			$result .= Entities::$entity_map[$m[1][0]];
			$html = substr($html, $m[0][1] + strlen($m[0][0]));
		}
		return $result . $html;
	}

	private static function load_entity_map() {
		Entities::$entity_map = array();
		Entities::load_entity_map_from('xhtml-lat1.ent');
		Entities::load_entity_map_from('xhtml-symbol.ent');
		Entities::load_entity_map_from('xhtml-special.ent');

		Entities::$entity_regex = '/&(' . implode('|', array_keys(Entities::$entity_map)) . ');/';
	}

	private static function load_entity_map_from($file) {
		global $SETTINGS;
		$body = file_get_contents($SETTINGS['LIBRARY_PATH'] . $file);
		preg_match_all('/<!ENTITY\s+([A-Za-z0-9]+)\s+"(&#[0-9]+;)">/', $body, $ma, PREG_SET_ORDER);
		foreach ($ma as $m) {
			Entities::$entity_map[$m[1]] = $m[2];
		}
	}
}

